import {
    My
} from './my.model'
import Toast from '@vant/weapp/toast/toast'
const my = new My()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isAuth: false, // 是否授权
        userInfo: '', // 用户信息
        messageNumber: ''
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        let that = this
        that.getTabBar().init() // 切换标签
        that._loadData()
    },

    /**
     * 获取所有数据
     */
    _loadData() {
        let that = this
        // 是否授权
        wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    that.getUserData()
                    // that.getMessageNumber()
                }
            }
        })
    },

    /**
     * 获取用户数据
     */
    getUserData() {
        let that = this
        const userInfo = my.getStorage('userInfo')
        if (userInfo) {
            that.setData({
                isAuth: true,
                userInfo: userInfo
            })
        } else {
            my.getUserData().then((res) => {
                my.setStorage('userInfo', res.data)
                that.setData({
                    isAuth: true,
                    userInfo: res.data
                })
            })
        }
    },

    /**
     * 获取未读消息个数
     */
    getMessageNumber() {
        let that = this
        my.getMessageNumber().then((res) => {
            if (res.data > 0) {
                that.setData({
                    messageNumber: res.data
                })
            }
        })
    },

    /**
     * 授权后获取用户信息
     * @param {*} options
     */
    onGetUserInfo(options) {
        let that = this
        // 用户允许授权
        if (options.detail.userInfo) {
            my.updateUserData(options.detail.userInfo).then((res) => {
                my.setStorage('userInfo', res.data)
                Toast.success('登录成功')
                that.setData({
                    isAuth: true,
                    userInfo: res.data
                })
            })
        }
    },

    /**
     * 跳到订单指定页面
     * @param {*} options
     */
    onSwitchOrder(options) {
        let status = my.getDataSet(options, 'id')
        wx.reLaunch({
            url: `/pages/order/order?status=${status}`,
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        return {
            title: '哈尔滨机动车检测协会提供支持',
            path: '/pages/index/index'
        }
    }
})